package com.adams.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.context.SecurityContextHolder;

import com.adams.access.db.bean.Menu;
import com.adams.access.db.bean.Right;
import com.adams.access.db.bean.User;
import com.adams.security.dao.VASUser;
import com.adams.sys.menu.service.MenuService;
import com.adams.sys.security.UserDetailsService;
import com.adams.user.service.UserService;
import com.adams.utils.SpringBeanFactoryUtil;


/**
 * 
 * 
 * File Name : Certificate.java
 * 
 * @Description : 证书处理类
 * @author 902990封文进
 */
public class Certificate
{
	private static Map<String, User> userMap = new HashMap<String, User>();

	private static Map<String, List<Menu>> rightMap = new HashMap<String, List<Menu>>();

	public static boolean isValidate = true;

	/**
	 * 
	 * Description : 根据用户名和密码创建证书
	 * 
	 * @param userName
	 * @param password
	 * @return boolean
	 * 
	 */
	public static boolean create(HttpServletRequest request, String userName,
			String password, String validateCode)
	{
		if (isValidate)
		{
			// 判断验证码输入是否正确
			String realValidateCode = (String) request.getSession()
					.getAttribute(Constants.CODE);
			if (!validateCode.equals(realValidateCode))
			{
				request.setAttribute("msg",
						Constants.LOGIN_FAIL_VALIDATECODE_ERROR);
				return false;
			}
		}

		User user = Certificate.queryUser(userName);
		// 判断用户和密码是否正确
		if (user == null
				|| !user.getPassword().equals(DigestUtils.md5Hex(password)))
		{
			request.setAttribute("msg", Constants.LOGIN_FAIL_PASSWD_ERROR);
			return false;
		}
		// 判断用户是否已分配角色
		if (!Constants.SUPER_USER_NAME.equals(userName)
				&& user.getRole() == null)
		{
			request.setAttribute("msg", Constants.LOGIN_FAIL_ROLE_NULL);
			return false;
		}

		// 存储用户权限
		MenuService menuService = (MenuService) SpringBeanFactoryUtil
				.getBean("menuService");
		List<Menu> list;
		if (!Constants.SUPER_USER_NAME.equals(userName))
		{
			list = new ArrayList<Menu>();
			Set<Right> rights = user.getRole().getRights();
			Iterator<Right> itor = rights.iterator();
			Menu menu;
			while (itor.hasNext())
			{
				menu = menuService.queryByCode(itor.next().getRightCode());
				if (menu != null)
				{
					list.add(menu);
				}
			}
		} else
		{
			list = menuService.queryAll();
		}
		userMap.put(user.getUserName(), user);
		rightMap.put(user.getUserName(), list);

		HttpSession session = request.getSession();
		session.setAttribute("user", user);
		return true;
	}

	/**
	 * 
	 * Description : 销毁证书
	 * 
	 * 
	 */
//	public static void destroy(HttpServletRequest request)
//	{
//		HttpSession session = request.getSession();
//		User user = (User) session.getAttribute("user");
//
//		if (user != null)
//		{
//			userMap.remove(user.getUserName());
//			rightMap.remove(user.getUserName());
//		}
//
//		session.setAttribute("user", null);
//	}

	/**
	 * 
	 * Description : 权限验证
	 * 
	 * @param user
	 * @param actionUrl
	 * @return boolean
	 * 
	 */
	public static boolean validate(HttpServletRequest request, User user,
			String actionUrl)
	{
		// 超级用户不需要验证
		if (Constants.SUPER_USER_NAME.equals(user.getUserName()))
		{
			return true;
		}
		// 获取请求参数
		String businessId = request.getParameter("businessId");
		String entryMenuId = request.getParameter("entryMenuId");
		// 检查权限
		List<Menu> list = rightMap.get(user.getUserName());
		String url;
		for (Menu menu : list)
		{
			if (menu.getUrl().indexOf("!") < 0)
			{
				continue;
			}
			url = menu.getUrl().substring(0, menu.getUrl().indexOf("!"));
			if (businessId != null && menu.getBusiness() != null
					&& menu.getBusiness().equals(businessId))
			{
				return true;

			} else if (entryMenuId != null
					&& menu.getId().toString().equals(entryMenuId))
			{
				return true;

			} else if (actionUrl.indexOf(url) >= 0)
			{
				return true;
			}
		}

		return false;
	}

	/**
	 * 
	 * Description : 获取证书的用户
	 * 
	 * @return User
	 * 
	 */
	public static User getUser(HttpServletRequest request){
		VASUser userDetails = (VASUser) SecurityContextHolder.getContext().
	    	getAuthentication().getPrincipal();
		if (userDetails == null){
			throw new RuntimeException(Constants.OVER_TIME);

		} else{
			return userDetails.getUser();
		}
	}

	/**
	 * 
	 * Description : 获取权限
	 * 
	 * @return
	 * 
	 */
	public static List<Menu> getRights(HttpServletRequest request){
		User user=(User)UserDetailsService.getUser();
		MenuService menuService = (MenuService) SpringBeanFactoryUtil.getBean("menuService");
		List<Menu> list;
		if (!Constants.SUPER_USER_NAME.equals(user.getUserName())){
			list = new ArrayList<Menu>();
			Set<Right> rights = user.getRole().getRights();
			Iterator<Right> itor = rights.iterator();
			Menu menu;
			while (itor.hasNext())
			{
				menu = menuService.queryByCode(itor.next().getRightCode());
				if (menu != null){
					list.add(menu);
				}
			}
		} else{
			list = menuService.queryAll();
		}
		return list;
	}

	/**
	 * 
	 * Description : 查询用户
	 * 
	 * @param userName
	 * @return
	 * 
	 */
	public static User queryUser(String userName)
	{
		UserService userService = (UserService) SpringBeanFactoryUtil
				.getBean("userService");
		return userService.queryByName(UserDetailsService.getUser().getUserName());
	}

	/**
	 * Description : 根据menuId获取顶层菜单
	 * 
	 * @param request
	 * @param menuId
	 * @return
	 */

	public static Long getTopMenu(List<Menu> menuList, Menu menu)
	{
		Menu temp=menu;
		while (temp.getParentId() != 0)
		{
			for (Menu menu1 : menuList)
			{
				if (menu1.getId().equals(temp.getParentId()))
				{
					temp = menu1;
					break;
				}
			}
		}
		return temp.getId();
	}
}
